//
//  QuXuanKeVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/20.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QuXuanKeVC.h"
#import "QuXuanKeCell.h"

#import "ShaiXuanViewController.h"



#import "AdetailViewController.h"


//#define xueduan_id @"xueduan_id"
//#define xueke_id @"xueke_id"
//#define nianji_id @"nianji_id"
//#define knowledge_point_id @"knowledge_point_id"
//#define course_type @"course_type"
//#define is_free @"is_free"
//#define list_type @"list_type"



//@"xueduan_id":@""  // 学段id
//,@"xueke_id":@""  // 学科id
//,@"nianji_id":@""  //年级id
//,@"knowledge_point_id":@"" //知识点id
//,@"page":@"1"
//,@"page_count":@"10"
//,@"course_type":@"" // 1 直播 2微课 3套餐
//,@"is_free":@""  // 是否免费 1免费 0付费
//,@"list_type":@"" //





static NSString *ident = @"QuXuanKeCell";
@interface QuXuanKeVC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic,strong)NSMutableArray *premarArr;

@property(nonatomic,strong)NSMutableArray *rightArr;


//@property(nonatomic,strong)NSMutableArray *shaiXuanArr;


@property(nonatomic,strong)NSMutableDictionary *shaiXuanDic;



@end

@implementation QuXuanKeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
        self.view.backgroundColor =[UIColor whiteColor];
    
    NSLog(@"%@",self.teskID);
    
    [self getdate];
    
    [self.view addSubview:self.tableView];
    
    UIBarButtonItem *shaxuan = [[UIBarButtonItem alloc]initWithTitle:@"筛选" style:(UIBarButtonItemStyleDone) target:self action:@selector(open)];
    
    
    UIBarButtonItem *queren = [[UIBarButtonItem alloc]initWithTitle:@"确认" style:(UIBarButtonItemStyleDone) target:self action:@selector(queRen)];
    
    
    
    self.navigationItem.rightBarButtonItems =@[shaxuan,queren];
    
}




#pragma mark ----------------------- 确认选择 提交数据  ------------------------
- (void)queRen {
    
    
    if (self.rightArr.count <= 0) {
        
         [MBProgressHUD showTextOnly:self.view message:@"请添加试题" delay:3];
        
        return;
        
    }
    
    NSString* idstr = @"";
    for (NSString *str in self.rightArr) {
        
        NSString *temp = [NSString stringWithFormat:@"%@,",str];
        
        idstr = [idstr stringByAppendingString:temp];
        
        
    }
    idstr = [idstr substringToIndex:idstr.length - 1];

    NSLog(@"%@",  idstr);
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body = @{@"task_id":self.teskID,
                       @"course_ids":idstr };
    
    NSString *lastUrl  = @"g=Client&m=Task&a=addCourse";
    
//    __weak __typeof(&*self)weakSelf = self;
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSString  *status = dic[@"status"];
        
        NNSLog(@"%@",dic);
        
        
        if ([status integerValue] == 200)
        {
            if (self.blockAdd)
            {
                self.blockAdd(@"1");
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
             [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}

-(NSMutableArray *)rightArr{
    if (!_rightArr) {
        _rightArr = [NSMutableArray array];
        
    }
    return  _rightArr;
}

#pragma mark ----------------------- 筛选 ------------------------
- (void)open {
    NSLog(@"筛选");
    
    ShaiXuanViewController *vc = [[ShaiXuanViewController alloc]init];
    
    vc.shaiXuan = ShaiXuanTypekeTask;

    vc.shaiXuanDic = ^(id dictory) {
        
        
        self.shaiXuanDic = [Helper newShaiXuanFromDictionary:dictory];
        
        NSLog(@"dictory == %@",self.shaiXuanDic);
        
        
        self.pageIndex = 1;
        [self getdate];
        
    };
    
    
    
//    vc.block = ^(id arr) {
//        NSLog(@"筛选结果= %@",arr);
//
//        self.shaiXuanArr = [NSMutableArray array];
//        for (NSString *str in arr) {
//            [self.shaiXuanArr addObject:str];
//        }
//
//        self.pageIndex =1;
//        [self getdate];
//
//    };
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        vc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }
    else
    {
        self.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    
    vc.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    [self.tabBarController presentViewController:vc animated:YES completion:nil];
}

#pragma mark -----------------------获取列表数据------------------------
-(void)getdate{

    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body = @{@"xueduan_id":@""  // 学段id
                       ,@"xueke_id":@""  // 学科id
                       ,@"nianji_id":@""  //年级id
                       ,@"knowledge_point_id":@"" //知识点id
                       ,@"page":[NSString stringWithFormat:@"%zd",self.pageIndex]
                       ,@"page_count":@"10"
                       ,@"course_type":@"" // 1 直播 2微课 3套餐
                       ,@"is_free":@""  // 是否免费 1免费 0付费
                       ,@"task":@"renwu"
//                       ,@"list_type":@"" //     列表类型,是直播的时候才有 直播：zhibo 预告：yugao 回放：huifang
                       };
    
    
    // 筛选参数
    if (self.shaiXuanDic.count > 0) {
        
        
        
        
//        ShaiXuan *s = [[ShaiXuan alloc]initWithDictionary:[Helper shaiXuanFromArr:self.shaiXuanArr]];
        
        ShaiXuan *s = [[ShaiXuan alloc]initWithDictionary:self.shaiXuanDic];

        parameter.body = @{@"xueduan_id":s.xueDuan  // 学段id
                           ,@"xueke_id":s.xueKe  // 学科id
                           ,@"nianji_id":s.nianJi //年级id
                           ,@"knowledge_point_id":s.zhiShiDian //知识点id
                           ,@"page":[NSString stringWithFormat:@"%zd",self.pageIndex]
                           ,@"page_count":@"10"
                           ,@"course_type":s.fenlei // 1 直播 2微课 3套餐
                           ,@"is_free":s.leiXing  // 是否免费 1免费 0付费
                           ,@"task":@"renwu"
//                           ,@"list_type":@"" //     列表类型,是直播的时候才有 直播：zhibo 预告：yugao 回放：huifang
                           };

    }

    
    
    NSString *lastUrl  = @"g=Client&m=Course&a=liveList";
    
    
    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        

        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];
        
        NSMutableArray *arr = [NSMutableArray array];
        
        arr = dic[@"data"][@"course_list"];
        
        if (arr.count > 0)
        {
            if (weakSelf.pageIndex == 1)
            {
                [weakSelf.dataArray removeAllObjects];
            }
            for (NSDictionary *dic in arr)
            {

                [weakSelf.dataArray addObject:dic];
            }
        }
        
        NSLog(@"course_list = %@ =",weakSelf.dataArray);


        [weakSelf.tableView reloadData];

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}




-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView {
    if (!_tableView) {
        UITableView *  tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
//        tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
//        tableView.scrollIndicatorInsets = _tableView.contentInset;
        
        
        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        //        [tableView registerClass:[WoTableViewCell class] forCellReuseIdentifier:identfire];
        //        [tableView registerClass:[WoHeaderCell class] forCellReuseIdentifier:identHead];
        
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            weakSelf.pageIndex = 1;
            
            [self.shaiXuanDic removeAllObjects];
            
            [weakSelf getdate];
            

        }];
        
        //         上拉加载
        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            if ( weakSelf.pageIndex < -1 ) {  weakSelf.pageIndex = 1;  }
            
            weakSelf.pageIndex++;
            
             [weakSelf getdate];
            

        }];
        _tableView = tableView;
        
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    QuXuanKeCell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];

    cell.nameLable.text = c.name;
    cell.jiageLabel.text = [NSString stringWithFormat:@"%zd学豆",[c.price integerValue]];
    [cell.iamgeView sd_setImageWithURL:[NSURL URLWithString:c.image_url] placeholderImage:PlaceHoldImage];
    
    cell.pingTalLabel.layer.borderColor = [UIColor redColor].CGColor;
    
    cell.pingTalLabel.layer.borderWidth = 1;
    
    cell.pingTalLabel.font = [UIFont systemFontOfSize:15];
    
    cell.pingTalLabel.edgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    
    BTN_MSG_FUNC(cell.addButton, addSender:);
    
    if ([self.rightArr containsObject:c.id])
    {
        [cell.addButton setImage:[UIImage imageNamed:@"删除-1"] forState:0];
    }
    else
    {
        [cell.addButton setImage:[UIImage imageNamed:@"添加"] forState:0];
    }

    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//    AdetailViewController *VC= [[AdetailViewController alloc]init];
//
//    Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];
//
//    VC.course_id = c.id;
//
//    [self.navigationController pushViewController:VC animated:YES];
    
    Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];
    [Helper keChengDetailFromVC:self course_id:c.id];
    
      
}


#pragma mark ----------------------- 添加 ------------------------
-(void)addSender:(UIButton *)sender{
    
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(QuXuanKeCell *)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
    
    NSLog(@"删除课程");
    
     Course *c = [[Course alloc]initWithDictionary:self.dataArray[myIndex.row]];
    
    
    
    if ([self.rightArr containsObject:c.id]) {
        [self.rightArr removeObject:c.id];
    }else{
       [self.rightArr addObject:c.id];
    }
    [self.tableView reloadData];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
